<template>
  <div class="post-book">
    <el-form 
      ref="formRef"
      :model="bookForm"
      :rules="rules"
      label-width="100px"
      class="book-form"
    >
      <!-- 书籍标题 -->
      <el-form-item label="书籍标题" prop="title">
        <el-input v-model="bookForm.title" placeholder="请输入书籍标题" />
      </el-form-item>

      <!-- 作者 -->
      <el-form-item label="作者" prop="author">
        <el-input v-model="bookForm.author" placeholder="请输入作者姓名" />
      </el-form-item>

      <!-- 标签 -->
      <el-form-item label="标签" prop="tags">
        <el-select
          v-model="bookForm.tags"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="请选择或输入标签"
          @change="handleTagsChange"
        >
          <el-option
            v-for="tag in tagOptions"
            :key="tag"
            :label="tag"
            :value="tag"
          />
        </el-select>
      </el-form-item>

      <!-- 封面图片 -->
      <el-form-item label="封面图片" prop="images">
        <div class="image-list">
          <div 
            v-for="(image, index) in imageList" 
            :key="index"
            class="image-item"
          >
            <img :src="image.url" class="cover" />
            <div class="image-actions">
              <el-icon @click="removeImage(index)"><Delete /></el-icon>
            </div>
          </div>
          
          <div class="upload-container">
            <el-upload
              v-if="imageList.length < 3"
              class="cover-uploader"
              :show-file-list="false"
              :before-upload="beforeUpload"
              action="#"
            >
              <div class="upload-placeholder">
                <el-icon class="upload-icon"><Plus /></el-icon>
                <span>点击上传</span>
              </div>
            </el-upload>
            <div class="upload-tip">最多可上传3张图片</div>
          </div>
        </div>
      </el-form-item>

      <!-- 阅读链接 -->
      <el-form-item label="阅读链接" prop="reading_url">
        <el-input 
          v-model="bookForm.reading_url" 
          placeholder="请输入阅读链接（选填）" 
        />
      </el-form-item>

      <!-- 读后感 -->
      <el-form-item label="读后感" prop="thoughts">
        <el-input
          v-model="bookForm.thoughts"
          type="textarea"
          :rows="6"
          placeholder="请分享您的读后感..."
        />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item class="form-actions">
        <el-button @click="saveDraft">保存</el-button>
        <el-button type="primary" @click="submitPost">发布</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDraftById, updateDraft, publishDraft } from '@/api/draft'
import { compressImage, validateImage } from '@/utils/imageUtils'

const route = useRoute()
const router = useRouter()
const draftId = route.params.id
const formRef = ref(null)
const imageList = ref([])

// 表单数据
const bookForm = ref({
  title: '',
  author: '',
  tags: [],
  reading_url: '',
  thoughts: ''
})

// 标签选项
const tagOptions = ref(['小说', '散文', '诗歌', '科幻', '悬疑', '励志'])

// 处理标签变化
const handleTagsChange = (value) => {
  if (value.length > 3) {
    ElMessage.warning('最多只能选择3个标签')
    bookForm.value.tags = value.slice(0, 3)
  }
}
// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入书籍标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  tags: [
    { required: true, message: '请至少选择一个标签', trigger: 'change' },
    { type: 'array', max: 3, message: '最多选择 3 个标签', trigger: 'change' }
  ],
  thoughts: [
    { required: true, message: '请输入读后感', trigger: 'blur' },
    { min: 5, max: 3000, message: '长度在 5 到 3000 个字符', trigger: 'blur' }
  ]
}

// 加载草稿数据
const loadDraft = async () => {
  try {
    const response = await getDraftById(draftId)
    if (response.code === 200) {
      const draft = response.data
      bookForm.value = {
        ...draft,
        tags: draft.tags ? draft.tags.split(/\s+/).filter(tag => tag) : []
      }
      document.title = `草稿编辑-${draft.title}`

      // 处理图片列表
      imageList.value = []
      if (draft.images) {
        try {
          const images = typeof draft.images === 'string' ? 
            JSON.parse(draft.images) : 
            draft.images
          images.forEach(url => {
            imageList.value.push({ url })
          })
        } catch (e) {
          console.error('解析图片数据失败:', e)
        }
      }
    }
  } catch (error) {
    console.error('加载草稿失败:', error)
    ElMessage.error('加载草稿失败')
  }
}

// 修改 beforeUpload 函数，使用压缩功能
const beforeUpload = async (file) => {
  try {
    validateImage(file, {
      maxSize: 10,
      allowedTypes: ['image/jpeg', 'image/png', 'image/gif']
    })

    if (imageList.value.length >= 3) {
      ElMessage.warning('最多只能上传3张图片!')
      return false
    }

    const compressedBase64 = await compressImage(file)
    imageList.value.push({
      file,
      url: compressedBase64
    })
    return false // 阻止自动上传
  } catch (error) {
    ElMessage.error(error.message || '图片处理失败')
    return false
  }
}

// 移除图片
const removeImage = (index) => {
  imageList.value.splice(index, 1)
}

// 保存草稿
const saveDraft = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    const draftData = {
      title: bookForm.value.title || null,
      author: bookForm.value.author || null,
      thoughts: bookForm.value.thoughts || null,
      tags: bookForm.value.tags?.length ? bookForm.value.tags.join(' ') : null,
      images: imageList.value.length ? JSON.stringify(imageList.value.map(img => img.url)) : null,
      reading_url: bookForm.value.reading_url || null
    }

    const response = await updateDraft(draftId, draftData)
    if (response.code === 200) {
      ElMessage.success('保存成功')
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存草稿失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  }
}

// 发布草稿
const submitPost = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    await ElMessageBox.confirm('确定要发布这篇文章吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })

    // 使用发布草稿的 API
    const response = await publishDraft(draftId)
    if (response.code === 200) {
      ElMessage.success('发布成功')
      window.close() // 关闭当前标签页
    } else {
      ElMessage.error(response.message || '发布失败')
    }
  } catch (error) {
    if (error === 'cancel') return
    console.error('发布失败:', error)
    ElMessage.error('发布失败，请稍后重试')
  }
}

onMounted(() => {
  loadDraft() // 组件加载时获取草稿数据
})

// 组件销毁时清理
onBeforeUnmount(() => {
  imageList.value.forEach(image => {
    URL.revokeObjectURL(image.url)
  })
})
</script>

<style scoped>
.post-book {
  padding: 40px;
  background-color: #fff;
  height: 100vh;
  box-sizing: border-box;
}

.book-form {
  max-width: 800px;
  margin: 40px auto 0;
}

.cover-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
}

.cover-uploader :deep(.el-upload) {
  width: 100%;
  height: 100%;
}

.cover-uploader :deep(.el-upload-dragger) {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #8c939d;
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.form-actions {
  margin-top: 40px;
}

.form-actions :deep(.el-form-item__content) {
  justify-content: flex-start;
  gap: 20px;
}

.image-list {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.image-item {
  position: relative;
  width: 150px;
  height: 150px;
  border-radius: 6px;
  overflow: hidden;
}

.image-actions {
  position: absolute;
  top: 0;
  right: 0;
  padding: 8px;
  background-color: rgba(0, 0, 0, 0.5);
  border-bottom-left-radius: 6px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-item:hover .image-actions {
  opacity: 1;
}

.image-actions .el-icon {
  color: #fff;
  font-size: 18px;
  cursor: pointer;
}

.upload-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  text-align: center;
  width: 150px;  /* 与上传框宽度一致 */
}
</style>
